package bootstrap;

import Config.RegistryConfig;
import Config.RpcConfig;
import boot.RpcApplication;
import model.ServiceInfo;
import model.ServiceRegisterInfo;
import register.LocalRegistry;
import register.Registry;
import register.RegistryFactory;
import server.HttpServer;
import server.VertHttpServer;

import java.util.List;

public class ProviderBootstrap {
    public static void init(List<ServiceRegisterInfo> serviceRegisterInfoList){
        // RPC 框架初始化
        RpcApplication.init();
        for(ServiceRegisterInfo serviceRegisterInfo : serviceRegisterInfoList) {

            // 注册服务
            String serviceName = serviceRegisterInfo.getServiceName();
            LocalRegistry.registService(serviceName, serviceRegisterInfo.getImplClass());

            // 注册服务到注册中心
            RpcConfig rpcConfig = RpcApplication.getRpcConfig();
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceInfo serviceMetaInfo = new ServiceInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServiceHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServicePort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + "服务注册失败：" + e);
            }
        }

        // 启动 web 服务
        HttpServer httpServer = new VertHttpServer();
        httpServer.doStart(RpcApplication.getRpcConfig().getServicePort());
    }
}
